package View;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

import Controller.MainController;
import Model.Connection;


public class Client extends Thread{
	private Socket client;
	
	public Client(){
		start();
	}
	
	public void run(){
		Login(3007, LoginView.user, LoginView.password);
	}
	
	public void Login(int port, String user, String password){
		
		try {
			System.out.println("Connecting to server ..........");
			client = new Socket("", port);
			System.out.println("Connection Established.");  

			OutputStream os = client.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			
			InputStream is = client.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			
			
			byte[] bytes = new byte[1024*1024];
			
			String[] sendInfor = new String[2];
			sendInfor[0] = user;
			sendInfor[1] = password;
			
			for(int i = 0; i < sendInfor.length; i++){
				System.out.println("Send " + sendInfor[i]);
				oos.writeUTF(sendInfor[i]);
				oos.flush();
			}
			
			String receive = ois.readUTF();
			System.out.println("receive: " + receive);
			if(receive.compareTo("1") == 0){
				Connection.socket = this.client;
				Connection.port = port;
				CommanderClient cmdClient = new CommanderClient(null);
				Connection.clientThread = cmdClient;
				MainController.CloseView(MainController.LOGIN_VIEW_NAME);
				MainController.OpenMainView();
				
			}else{
				//hien thong bao login that bai		
				JOptionPane.showMessageDialog(null, "User or password is incorrect!", 
					    "Error", JOptionPane.ERROR_MESSAGE);
			}
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//JOptionPane.showMessageDialog(ViewScreen.frame, "Unknown Host!");
			JOptionPane.showMessageDialog(null, "Can not connect to server!", 
				    "Error", JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//JOptionPane.showMessageDialog(ViewScreen.frame, "Connection failed!");
			JOptionPane.showMessageDialog(null, "Can not connect to server!", 
				    "Error", JOptionPane.ERROR_MESSAGE);
		}
		
	}
	
	public void SendCommand(int port)
	{
		
	}
}
